package au.edu.unsw.editingtool.web.limited;

import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.xpath.XPathExpressionException;

import org.xml.sax.SAXException;

import au.edu.unsw.editingtool.db.DBEditingpool;
import au.edu.unsw.editingtool.fedora.FedoraFactory;
import au.edu.unsw.editingtool.global.EditingToolException;
import au.edu.unsw.editingtool.global.EditingToolGlobalConstant;
import au.edu.unsw.editingtool.global.EditingToolPropertyReader;
import au.edu.unsw.editingtool.global.EditingToolRedirectPageException;
import au.edu.unsw.editingtool.global.EditingToolUtil;
import au.edu.unsw.editingtool.transformxml.XMLProcessor;

/**
 * Servlet implementation class Editing
 */
public class EditMetaData extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String datastreamID = "";
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public EditMetaData() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doService(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doService(request, response);
	}


	
	private FedoraFactory setupFedora(HttpServletRequest request, EditingToolPropertyReader reader) throws IOException {
		
		Hashtable<String, String> properties = EditingToolUtil.getProperties(reader, EditingToolPropertyReader.FEDORA);
		this.datastreamID = properties.get("datastream");
		
		return new FedoraFactory(properties.get("host") + ":" + properties.get("port") + properties.get("path"), 
												 properties.get("username"), properties.get("password"));
	}
	
	private Hashtable<String, String> grabFormData(String valetXML) throws XPathExpressionException, ParserConfigurationException, SAXException, IOException {
		// plan is very simple, make all of them as textareas.
		// An example for the label, description_label -> Description Label:
		
		return EditingToolUtil.getNodeListViaPath("//Formdata", valetXML);
	}
	
	private void populateIntoEditingPool(HttpServletRequest request, FedoraFactory fedora) throws ClassNotFoundException, SQLException, EditingToolRedirectPageException {
		
		DBEditingpool editingpool = new DBEditingpool();
		String status = editingpool.checkStatus(request.getParameter(EditingToolGlobalConstant.requestPid));
		String editor = request.getParameter(EditingToolGlobalConstant.requestUsername);
		String publication = request.getParameter(EditingToolGlobalConstant.requestPid);
		String version = fedora.getDatastreamVersionID(publication, this.datastreamID);
		if (status == null) {		
			Hashtable<String, String> record = new Hashtable<String, String>();
			record.put("Publication", publication);
			record.put("Editor", editor);
			record.put("Version", version);
			editingpool.addNewRecord(record);			
		} else if (status.equals(EditingToolGlobalConstant.editingpoolStatusSubmit)) {
			if (editingpool.isAuthor(editor, publication)) {
				editingpool.editingAgain(publication, version);
			} else {
				EditingToolRedirectPageException e = new EditingToolRedirectPageException();
				e.setPage("unavailable.jsp?reason=" + EditingToolGlobalConstant.redirectPageWaitingForReview);
				throw e;
			}
		} else {
			EditingToolRedirectPageException e = new EditingToolRedirectPageException();
			e.setPage("unavailable.jsp?reason=" + status);
			throw e;
		}
		
	}
	
	protected void doService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String servletContext = getServletContext().getRealPath("") + EditingToolGlobalConstant.fileSeparator;
		String valetXML = ""; 
		
		try {
			
			EditingToolPropertyReader reader = new EditingToolPropertyReader();
			reader.setFile(servletContext + EditingToolGlobalConstant.configFilePath);
			
			FedoraFactory fedora = this.setupFedora(request, reader);  
			
			this.populateIntoEditingPool(request, fedora);
			valetXML = EditingToolUtil.getValetXML(request.getSession(false).getId(), 
												   request.getParameter(EditingToolGlobalConstant.requestPid), this.datastreamID, fedora, reader);
			sendFormData(grabFormData(valetXML), request, response);
			
		} catch (XPathExpressionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (EditingToolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TransformerConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (TransformerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (EditingToolRedirectPageException e) {
			response.sendRedirect(e.getPage());
		}
	}
	
	private void sendFormData(Hashtable<String, String> formData, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		RequestDispatcher dispatcher = request.getRequestDispatcher("/editPublication.jsp");
		request.setAttribute("pubTitle", "Edit Metadata");
		request.setAttribute("pubMessage", "When you finished, you can preview your change before submit.");
		request.setAttribute("pubButton", EditingToolGlobalConstant.buttonTypePreview);
		request.setAttribute("pubReadonly", "nouse");
		request.setAttribute(EditingToolGlobalConstant.requestFormAction, "editPublication.jsp");
		request.setAttribute(EditingToolGlobalConstant.requestCommandType, EditingToolGlobalConstant.commandEdit);
		request.setAttribute(EditingToolGlobalConstant.requestFormData, formData);
		dispatcher.forward(request, response);
	}
	
}
